package xhg.com.resell.base.httpbase;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import xhg.com.resell.application.Global;

/**
 * @author lew1210
 */
public class RetrofitHelper {
    private static final long TIME_OUT = 30;
    private static RetrofitHelper helper;
    private OkHttpClient.Builder builder;

    private Retrofit retrofit;

    private OkHttpClient client;

    private RetrofitHelper() {
        initOkHttpClient();
    }

    private void initOkHttpClient() {
        builder = new OkHttpClient.Builder();
        builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);

        //设置是否打印请求结果
        if (Global.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(interceptor);
        }

    }

    public static RetrofitHelper getInstance() {
        if (helper == null) {
            synchronized (RetrofitHelper.class) {
                if (helper == null) {
                    helper = new RetrofitHelper();
                }
            }
        }
        return helper;
    }

    public void init(String url) {
        init(builder, url);
    }

    public void init(OkHttpClient.Builder builder, String url) {
        if (builder == null) {
            client = this.builder.build();
        } else {
            client = builder.build();
        }

        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(url)
                .addConverterFactory(ResponseConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public OkHttpClient.Builder getBuilder() {
        return builder;
    }

    public <T> T getRetrofit(Class<T> cls) {
        return retrofit.create(cls);
    }




}
